<template>
  <div class="alert-list">
    <!-- 查询表单 -->
    <div class="header">
      <el-form ref="ruleFormRef" :inline="true" :model="queryParams" :rules="rules" class="demo-form-inline">
        <div>
          <div>
            <el-form-item label="MAC" prop="mac">
              <el-input v-model="queryParams.mac" placeholder="请输入MAC地址" />
            </el-form-item>
            <el-form-item label="设备编号" prop="deviceIds">
              <el-input v-model="queryParams.deviceIds" placeholder="请输入设备编号" style="width: 240px" clearable />
            </el-form-item>

            <el-form-item label="告警类型" prop="warnType">
              <el-select v-model="queryParams.warnType" placeholder="请选择" style="width: 240px" clearable>
                <el-option v-for="item in warnTypes" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="时间范围" prop="timeRange">
              <el-date-picker style="width: 220px;" v-model="timeRange" type="datetimerange" range-separator="-"
                start-placeholder="开始时间" end-placeholder="结束时间" value-format="YYYY-MM-DD HH:mm:ss"
                :default-time="defaultTime" @change="handleTimeChange" clearable />
            </el-form-item>
            <div style="display: flex; margin-top: 20px;">
              <el-form :model="queryParams" ref="formRef" v-if="isDepart">
                <el-form-item label="省/市/区" prop="area" v-if="isExpanded">
                  <region-selector style="width: 500px" ref="regionSelectorRef" v-model="queryParams.area"
                    @change="handleRegionChange" />
                </el-form-item>
              </el-form>
              <div v-if="isDepart">
                <el-form-item label="部门" prop="masterDeptId" v-if="isExpanded">
                  <el-cascader v-model="queryParams.masterDeptId" :options="firstList" placeholder="请选择部门"
                    @change="onDepartmentChange" :props="props1" clearable />
                </el-form-item>
              </div>
            </div>
          </div>

        </div>
        <div class="button-group" style="width: 256px; margin-right: 20px;">
          <el-button type="primary" :icon="Search" @click="handleQuery(ruleFormRef)">查询</el-button>
          <el-button :icon="Refresh" @click="resetQuery(ruleFormRef)">重置</el-button>
          <el-button @click="toggleExpand" v-if="isDepart">
            {{ isExpanded ? '收起' : '展开' }}
          </el-button>
        </div>
      </el-form>
    </div>
    <!-- 表格部分 -->
    <div class="footer">
      <div class="f">
        <div class="util">
          <span>告警列表</span>
        </div>
      </div>
      <div class="table-inner">
        <el-table v-loading="loading" :data="tableData" style="width: 100%" border :max-height="600">
          <el-table-column prop="id" label="序号" align="center" width="80">
            <template #default="scope">
              {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="deviceId" label="设备编号" align="center" show-overflow-tooltip>
            <template #default="{ row }">
              <span class="copy-text" @click="handleCopy(row.deviceId)">{{ row.deviceId }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="mac" label="MAC" :show-overflow-tooltip="true" align="center">
            <template #default="{ row }">
              <span class="copy-text" @click="handleCopy(row.mac)">{{ row.mac }}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="ip" label="IP" align="center" />-->
          <!-- <el-table-column prop="ssid" label="告警名称" align="center" show-overflow-tooltip /> -->
          <el-table-column prop="hotelName" label="酒店名称" align="center" show-overflow-tooltip v-if="isDepart">
            <template #default="scope">
              {{ scope.row.hotelName ? scope.row.hotelName : '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="address" label="酒店地址" :show-overflow-tooltip="true" align="center" v-if="isDepart">
            <template #default="{ row }">
              <span class="copy-text" @click="handleCopy(row.address)">{{ row.address }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="textArea" label="详细地址" align="center" v-if="isDepart" :show-overflow-tooltip="true">
            <template #default="{ row }">
              {{ row.textArea ? row.textArea : '-' }}
            </template>
          </el-table-column>
          <!-- <el-table-column prop="rssi" label="信号强度" align="center" width="150">
          <template #default="scope">
            {{ scope.row.rssi ? scope.row.rssi : '-' }}
          </template>
        </el-table-column> -->
          <el-table-column prop="warnSite" label="告警地点" align="center" />
          <!-- 告警类型列 -->
          <el-table-column prop="warnType" label="告警类型" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.warnType !== null" :type="getWarnTypeTagType(scope.row.warnType)">
                {{ getWarnTypeLabel(scope.row.warnType) }}
              </el-tag>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <!-- 告警次数列 -->
          <el-table-column prop="warnNum" label="告警次数" align="center" sortable>
            <template #default="scope">
              <el-tag v-if="scope.row.warnNum !== null" :type="getWarnNumTagType(scope.row.warnNum)">
                {{ scope.row.warnNum }}
              </el-tag>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <!-- 信号强度列 -->
          <el-table-column prop="rssi" label="信号强度" align="center" width="120">
            <template #default="scope">
              {{ scope.row.rssi }}
              <el-progress :text-inside="true" :show-text="false" :stroke-width="6" v-if="scope.row.rssi !== null"
                :percentage="getRssiPercentage(scope.row.rssi)" :status="getRssiStatus(scope.row.rssi)" />
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column prop="warnTime" label="告警时间" align="center" :show-overflow-tooltip="true">
            <template #default="scope">
              {{ scope.row.warnTime ? scope.row.warnTime : '-' }}
            </template>
          </el-table-column>
          <!-- 设备状态列 -->
          <el-table-column label="操作" align="center" fixed="right" width="250">
            <template #default="scope">
              <el-switch v-model="scope.row.status" :active-value="0" :inactive-value="1" active-text="信任"
                inactive-text="不信任" @change="handleStatusChange($event, scope.row)" v-hasPermi="['gj:warn:trust']" />

              <span style="margin: 0 10px; font-size: 18px; color: rgba(0, 0, 0, 0.4); "></span>
              <el-button link type="primary" size="small" @click="handleDetail(scope.row)"
                v-hasPermi="['gj:warn:detail']">
                详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]" :total="total" background layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </div>
  </div>
  <!-- 详情对话框 -->
  <el-dialog v-model="dialogVisible" title="告警详情" width="800px" destroy-on-close>
    <el-descriptions :column="2" border>
      <el-descriptions-item label="设备编号">{{ detailData.deviceId }}</el-descriptions-item>
      <el-descriptions-item label="MAC地址">{{ detailData.mac }}</el-descriptions-item>
      <!--        <el-descriptions-item label="IP地址">{{ detailData.ip }}</el-descriptions-item>-->
      <el-descriptions-item label="主机名">{{ detailData.hostname }}</el-descriptions-item>
      <el-descriptions-item label="告警类型">
        <el-tag :type="getWarnTypeTagType(detailData.warnType)">
          {{ getWarnTypeLabel(detailData.warnType) }}
        </el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="告警次数">
        <el-tag :type="getWarnNumTagType(detailData.warnNum)">
          {{ detailData.warnNum }}
        </el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="告警位置">{{ detailData.warnSite }}</el-descriptions-item>
      <el-descriptions-item label="SSID">{{ detailData.ssid }}</el-descriptions-item>
      <el-descriptions-item label="AP MAC">{{ detailData.apMac }}</el-descriptions-item>
      <el-descriptions-item label="信号强度">{{ detailData.rssi }}</el-descriptions-item>
      <el-descriptions-item label="命中关键字" v-if="false">
        <el-tag type="danger" effect="dark" v-if="detailData.keywords">
          {{ detailData.keywords }}
        </el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="设备状态">
        <el-tag :type="detailData.status === 0 ? 'success' : 'danger'">
          {{ detailData.status === 0 ? '信任' : '不信任' }}
        </el-tag>
      </el-descriptions-item>
    </el-descriptions>
  </el-dialog>

  <!-- 设备状态对话框 -->
  <deviceList v-model:visible="stateDialog" :currentStatus='currentStatus' :currentRow="currentRow"
    @submit="confirmEdit" @cancel="cancelEdit">
  </deviceList>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, watch, computed } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { Search, Refresh, Download } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { warnPage, recoGjingize, deptOptions, collection } from '@/api/explore'
import RegionSelector from '@/components/RegionSelector'
import { useRoute } from 'vue-router'
import { debounce } from 'lodash';
import { useUserStore } from '@/store/modules/user'
import deviceList from './deviceList.vue'

const UserStore = useUserStore()
// 用户信息
const userInfo = computed(() => UserStore.userInfo)
console.log(userInfo.value, 'suerInfo')
const merMapId = userInfo.value.merMapId // 1表示酒店 0 上级
const firstList = ref<any[]>([]);//部门
const isDepart = ref(false);
const isExpanded = ref(false)
const route = useRoute()
const xrShow = ref(false)
const props1 = {
  checkStrictly: true,
}
if (merMapId) {
  xrShow.value = true
}
console.log(merMapId, '99999');

// 切换展开和收起状态
const toggleExpand = () => {
  isExpanded.value = !isExpanded.value;
};
// 告警类型选项
const warnTypes = [
  { label: 'AP告警', value: 1 },
  { label: 'STA告警', value: 2 },
  { label: '可疑摄像头', value: 3 }
]
// 查询参数
const queryParams = reactive({
  deviceIds: '',
  warnType: null,
  startTime: '',
  endTime: '',
  masterDeptId: '',
  deptIds: '',
  area: { province: '', city: '', area: '' },
  mac: '',
  pageNum: 1,
  pageSize: 10
})
// 复制功能
const handleCopy = (text) => {
  const input = document.createElement('input');
  input.value = text;
  document.body.appendChild(input);
  input.select();
  document.execCommand('copy'); // 执行复制
  document.body.removeChild(input); // 移除输入框

  ElMessage.success('复制成功！'); // 显示成功消息
};
const debouncedSubmit = debounce(async () => {
  await getList();
}, 500);
// 监听mac字段的变化
watch(() => queryParams.mac, debouncedSubmit);
// 父组件接收子组件的地址变化
const handleRegionChange = (data) => {
  console.log('地址数据:', data)
}
// 表单验证规则
const rules = reactive<FormRules>({

  warnType: [
    {
      pattern: /^[1-4]$/,
      message: '请选择正确的告警类型',
      trigger: 'change'
    }
  ]
})

// 时间选择器默认时间
const defaultTime = [
  new Date(2000, 1, 1, 0, 0, 0),
  new Date(2000, 1, 1, 23, 59, 59)
]

const ruleFormRef = ref<FormInstance>()
const loading = ref(false)
const tableData = ref([])
const total = ref(0)
const timeRange = ref([])
const dialogVisible = ref(false)
const detailData = ref({})
const stateDialog = ref(false)
const currentStatus = ref('')
interface DeviceRow {
  id: number | string;
  status: number;
  mac?: string;
}

const currentRow = ref<DeviceRow | null>(null)

// 获取告警类型标签
const getWarnTypeLabel = (type: number | null) => {
  if (type === null || type === undefined) return '未知类型'
  const found = warnTypes.find(item => item.value === type)
  return found ? found.label : '未知类型'
}

// 获取告警类型标签样式
const getWarnTypeTagType = (type: number | null) => {
  if (type === null || type === undefined) return ''
  const typeMap = {
    1: 'warning',  // MAC类型
    2: 'info',     // 品牌名称
    3: 'success',  // 主机名
    4: 'danger'    // IP
  }
  return typeMap[type] || ''
}

// 获取告警次数标签样式
const getWarnNumTagType = (num: number | null) => {
  if (num === null || num === undefined) return 'info'
  if (num >= 10) return 'danger'
  if (num >= 5) return 'warning'
  return 'info'
}

// 获取信号强度百分比
const getRssiPercentage = (rssi: number | null) => {
  // if (rssi === null || rssi === undefined) return 0
  // const percentage = Math.min(Math.max(((rssi + 100) / 100) * 100, 0), 100)
  // return Math.round(percentage)
  return Math.abs(rssi)
}

// 获取信号强度状态
const getRssiStatus = (rssi: number | null) => {
  if (rssi === null || rssi === undefined) return 'exception'

  // 如果是正数，先转换为对应的负数值
  const normalizedRssi = rssi > 0 ? -rssi : rssi

  // 信号强度判断
  if (normalizedRssi >= -50) return 'success'      // 0到-50 强信号
  if (normalizedRssi >= -70) return 'warning'      // -50到-70 中等信号
  return 'exception'                               // 低于-70 弱信号
}

// 使用示例
console.log(getRssiStatus(-30))  // 'success'
console.log(getRssiStatus(-60))  // 'warning'
console.log(getRssiStatus(-80))  // 'exception'
console.log(getRssiStatus(60))   // 'warning'  // 会被转换为-60处理
const editState = (event, row) => {
  // 创建状态对话框的引用
  stateDialog.value = true;
  currentStatus.value = 0;
  currentRow.value = row
  console.log(row, 'row');
};
const confirmEdit = async (data) => {
  if (!currentRow.value) {
    ElMessage.error('设备信息不完整');
    return;
  }
  const params = new URLSearchParams()
  params.append('id', currentRow.value.id)
  params.append('status', currentStatus.value)
  params.append('mac', currentRow.value.mac)

  try {
    await Promise.all([
      collection(data),
      recoGjingize(params, currentRow.value.id)
    ]);

    await getList();
    ElMessage.success('修改状态成功');
  } catch (error) {
    console.error('修改状态失败:', error);
    ElMessage.error('修改状态失败,请重试');
    await getList(); // 恢复数据
  } finally {
    stateDialog.value = false;
    // 重置状态
    currentStatus.value = '';
    currentRow.value = null;
  }
};

// 取消操作
const cancelEdit = () => {
  getList(); // 使用正确的函数名
  // ElMessage({
  //   type: 'info',
  //   message: '已取消修改',
  // });
  stateDialog.value = false;
};

// 处理设备状态变更
const handleStatusChange = async (event: number, row: any) => {
  if (!row || !row.id) {
    ElMessage.error('设备信息不完整')
    return
  }
  if (event) {
    // 直接调用状态修改的核心逻辑，移除多余的确认框
    try {
      const params = new URLSearchParams()
      params.append('id', row.id.toString())
      params.append('status', event.toString())
      await recoGjingize(params, row.id)
      ElMessage.success('状态更新成功')
    } catch (error) {
      console.error('更新设备状态失败：', error)
      // ElMessage.error('状态更新失败')
      row.status = event === 0 ? 1 : 0
    }
  } else {
    editState(event, row);
  }

}

// 处理时间范围变化
const handleTimeChange = (val: any) => {
  if (val) {
    queryParams.startTime = val[0]
    queryParams.endTime = val[1]
  } else {
    queryParams.startTime = ''
    queryParams.endTime = ''
  }
}

// 获取列表数据
const getList = async () => {
  loading.value = true
  try {
    const params = {
      deviceIds: queryParams.deviceIds ? queryParams.deviceIds : undefined,
      warnType: queryParams.warnType ? queryParams.warnType : undefined,
      masterDeptId: queryParams.mac ? queryParams.masterDeptId : undefined,
      deptIds: queryParams.masterDeptId ? queryParams.deptIds : undefined,
      startTime: queryParams.startTime ? queryParams.startTime : undefined,
      endTime: queryParams.endTime ? queryParams.endTime : undefined,
      tcProvince: queryParams.area.province,
      tcCity: queryParams.area.city,
      tcArea: queryParams.area.area,
      mac: queryParams.mac ? `%${queryParams.mac}%` : undefined,
      pageNum: queryParams.pageNum,
      pageSize: queryParams.pageSize
    };
    const res = await warnPage(params)
    tableData.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('获取告警列表失败：', error)
    ElMessage.error('获取列表数据失败')
  } finally {
    loading.value = false
  }
}
const getDeptOptions = async (val) => {
  const res = await deptOptions(val ? val : '')
  console.log(res, 'res');
  firstList.value = res.data
}
const onDepartmentChange = async (newDepartmentId) => {
  console.log(newDepartmentId, 'newDepartmentId');
  // 获取数组的最后一项
  const lastDepartmentId = newDepartmentId[newDepartmentId.length - 1];
  console.log(lastDepartmentId, 'lastDepartmentId');
  queryParams.deptIds = lastDepartmentId

  console.log(queryParams.deptIds, 'queryParams.value.deptIds');
};
// 查询按钮点击
const handleQuery = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      queryParams.pageNum = 1
      getList()
    }
  })
}

// 重置查询
const resetQuery = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  timeRange.value = []
  queryParams.startTime = ''
  queryParams.endTime = ''
  queryParams.pageNum = 1
  queryParams.area = { province: '', city: '', area: '' }
  getList()
}

// 导出数据
const handleExport = () => {
  const params = {
    ...queryParams,
    export: true
  }
  try {
    // const res = await exportWarningList(params)
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

// 删除记录
const handleDelete = async (row) => {
  try {
    // await deleteWarning(row.id)
    ElMessage.success('删除成功')
    getList()
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

// 查看详情
const handleDetail = (row) => {
  detailData.value = { ...row }
  dialogVisible.value = true
}

// 处理每页显示数量变化
const handleSizeChange = (val: number) => {
  queryParams.pageSize = val
  getList()
}

// 处理页码变化
const handleCurrentChange = (val: number) => {
  queryParams.pageNum = val
  getList()
}

// 页面加载时获取数据
onMounted(() => {
  const userInfo = computed(() => UserStore.userInfo)
  if (userInfo.value.merMapId === 0) {
    isDepart.value = true;
  } else {
    isDepart.value = false;
  }
  const { mac } = route.query
  if (mac) {
    queryParams.mac = mac
  }
  getList()
  getDeptOptions(null)
})
</script>

<style lang="scss" scoped>
.alert-list {
  .header {
    display: flex;
    padding: 16px 16px 0 16px;
    margin-bottom: 16px;
    border-radius: 4px;
    background: white;
    box-shadow: 0 0 12px rgb(0 0 0 / 5%);

    .demo-form-inline {
      width: 100%;
      display: flex;
      justify-content: space-between;
      margin-bottom: 20px;
    }

    .button-group {
      display: flex;
      gap: 10px;
      margin-bottom: 16px;
    }
  }

  .footer {
    flex: 1;
    display: flex;
    padding: 16px;
    flex-direction: column;
    border-radius: 4px;
    overflow: hidden;
    background: white;
    box-shadow: 0 0 12px rgb(0 0 0 / 5%);
    position: relative;
    box-sizing: border-box;

    .f {
      display: flex;
      justify-content: space-between;
      margin-bottom: 16px;
    }

    .util {
      display: flex;
      align-items: center;
    }

    .table-inner {
      flex: 1;
      position: relative;
    }
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  :deep(.el-form-item) {
    margin-right: 20px;
    margin-bottom: 0;
  }

  :deep(.el-table) {
    .el-progress {
      margin: 0;
      width: 90%;
    }

    .el-tag {
      margin: 0 2px;
    }

    .el-switch {
      margin: 0 auto;
    }
  }

  :deep(.el-dialog__body) {
    padding: 20px;
  }

  :deep(.el-descriptions) {
    padding: 20px;

    .el-descriptions__label {
      width: 120px;
      font-weight: bold;
    }
  }
}
</style>